<template>
    <div class="grid" :id="id">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, watch } from "vue";

const props = defineProps(["id", "width", "num"]);
const changeDisplay = () => {
    const grid = document.getElementById(props.id);
    if (!grid) return;
    const gridWidth = parseFloat(window.getComputedStyle(grid).width);
    const num = Math.floor(gridWidth / props.width);
    if (num <= props.num) {
        // 当一行可以容纳的元素个数小于子元素个数，开启grid布局
        grid.style.display = "grid";
        grid.style.gridTemplateColumns = `repeat(auto-fit, minmax(${props.width}px, 1fr))`;

        document.querySelectorAll(`#${props.id} > div`).forEach((el) => {
            el.style.width = "auto";
            el.style.minWidth = props.width + "px";
        });
    } else {
        grid.style.display = "flex";
        document.querySelectorAll(`#${props.id} > div`).forEach((el) => {
            el.style.width = props.width + "px";
            el.style.minWidth = "none";
        });
    }
};
watch(
    () => props.num,
    () => {
        changeDisplay();
    },
);

const handleResize = () => {
    changeDisplay();
};
onMounted(() => {
    changeDisplay();
    window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
});
</script>

<style lang="scss" scoped></style>
